package middleware

import (
	"net/http"

	"go-pan/internal/log"
	"go-pan/internal/model"
	"go-pan/internal/utils"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var user model.UserInfo

		// 从 Cookie 中获取 token
		token, err := c.Cookie("token")
		if err != nil || token == "" {
			// 没有 token → 匿名用户
			user = model.UserInfo{
				ID:      0,
				IsGuest: true,
			}
		} else {
			// 使用ValidateAccessToken验证token（包括黑名单检查）
			claims, parseErr := utils.ValidateAccessToken(token)
			if parseErr == nil {
				user = model.UserInfo{
					ID:       claims.UserID,
					Username: claims.Username,
					IsGuest:  false,
				}
			} else {
				// 检查是否是数据库错误
				if utils.IsDatabaseError(parseErr) {
					// 数据库错误 → 返回 500 Internal Server Error
					log.SystemLogger.Error("database error during token validation",
						zap.Error(parseErr),
						zap.String("ip", c.ClientIP()),
						zap.String("path", c.Request.URL.Path),
					)
					c.JSON(http.StatusInternalServerError, gin.H{
						"error":   "internal server error",
						"message": "failed to validate token due to database error",
					})
					c.Abort()
					return
				}
				// 无效 token → 匿名用户（认证失败，后续由 LoginMiddleware 返回 401）
				user = model.UserInfo{
					ID:      0,
					IsGuest: true,
				}
			}
		}

		c.Set("user", user)
		c.Next()
	}
}
